package com.dai.chun.dao.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.dai.chun.dao.model.Wage;
import com.dai.chun.util.DbExcel;


public class BackupAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
		/**
		 * 备份当月工资数据
		 * @return
		 *
		 */
		public String backupCurMonth() {
			
			return "backupCurMonth";
		}
		public void toExcel() {
			DbExcel de=new DbExcel();
			Wage w=new Wage();
			w.setWage_month(new SimpleDateFormat("yyyy-MM").format(new Date()));
			de.getData(w);
			String url = ServletActionContext.getServletContext().getRealPath("/");
			outFile(url+"test.xls", "1");
		}
		/**
		 * 导出文件让用户下载
		 * @param name
		 * @param desc
		 */
		private void outFile(String name,String desc){
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			File returnFile = new File(name);
			try {
				desc = URLEncoder.encode(desc+"表", "UTF-8");//编码URL避免文件名中文乱码，要UTF-8才行
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("charset=gbk;application/msxls");
	        response.setHeader("Content-disposition", "inline;filename="+desc+".xls");
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        try {
	            bis = new BufferedInputStream(new FileInputStream(returnFile));
	            bos = new BufferedOutputStream(response.getOutputStream());
	            byte[] buffer = new byte[2048];
	            int flag;
	            while((flag = bis.read(buffer, 0, buffer.length)) != -1) {
	                bos.write(buffer, 0, flag);
	            }
	            bos.flush();
	        } catch(Exception ex) {
	            ex.printStackTrace();
	        } finally {
	            try {
	                if(bis != null)
	                    bis.close();
	                if(bos != null)
	                    bos.close();
	                if(response.getOutputStream() != null){
	                	response.getOutputStream().flush();
	                	response.getOutputStream().close();
	                }
	            } catch(IOException ie) {
	                ie.printStackTrace();
	            }
	        }
		}

}
